/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlet;

import DAO.UserDAO;
import DTO.OrderDTO;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;
import org.apache.fop.apps.FOPException;
import org.xml.sax.InputSource;
import Config.Constants;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.transform.Source;
import sample.utils.FoUtils;

/**
 *
 * @author trungnm
 */
public class PrintPDFServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        //PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String user = (String) session.getAttribute("USER");
        String role = (String) session.getAttribute("ROLE");
        String action = request.getParameter("btnAction");
        UserDAO userDAO = new UserDAO();

        String url = Constants.MainPage;
        try {
            if (action.equals("printPDF")) {
                String path = getServletContext().getRealPath("/");
                String xslPath = path + "WEB-INF/FO/orderDetailFO.xsl";
                //String xmlPath = path + "WEB-INF/FO/orderDetailFO.xml";
                String foPath = path + "WEB-INF/FO/orderDetailFO.fo";
                long orderID = Long.parseLong(request.getParameter("orderID"));
                OutputStream sos = new ByteArrayOutputStream();
                userDAO.MarshallingOrderDetail(orderID, sos);

                InputStream xmlIS = new ByteArrayInputStream(((ByteArrayOutputStream) sos).toByteArray());
                Source source = new StreamSource(xmlIS);
                ByteArrayOutputStream bos = FoUtils.transformToPdf(path, source, xslPath);
//                methodTrAX(xslPath,sos,foPath);
//                File file = new File(foPath);
//                FileInputStream input = new FileInputStream(file);
//
//                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                response.setContentType("application/pdf");
//                Driver driver = new Driver(new InputSource(input), bos);
//                Logger log = new ConsoleLogger(ConsoleLogger.LEVEL_WARN);
//                driver.setRenderer(Driver.RENDER_PDF);
//                driver.run();
                byte[] content = bos.toByteArray();
                response.setContentLength(content.length);
                response.getOutputStream().write(content);
                response.getOutputStream().flush();
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PrintPDFServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            java.util.logging.Logger.getLogger(PrintPDFServlet.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
//            out.close();
        }
    }

    private void methodTrAX(String xslpath, OutputStream xmlOS, String output) {
        try {
//            FopFactory fopFactory = FopFactory.newInstance();
//            FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
//            String path = getServletContext().getRealPath("/");
//            File config = new File(path+"WEB-INF/FO/FOconfig.xconf");
//            fopFactory.setUserConfig(config);
//            Fop fop = fopFactory.newFop(MimeConstants.MIME_FOP_AREA_TREE, foUserAgent, out);

            TransformerFactory tf = TransformerFactory.newInstance();
            StreamSource xsltFile = new StreamSource(xslpath);
            Transformer trans = tf.newTransformer(xsltFile);
            InputStream xmlIS = new ByteArrayInputStream(((ByteArrayOutputStream) xmlOS).toByteArray());
            StreamSource xmlFile = new StreamSource(xmlIS);
            StreamResult htmlFile = new StreamResult(
                    new FileOutputStream(output));
            trans.transform(xmlFile, htmlFile);

        } catch (TransformerConfigurationException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
